package com.example.basesystem.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.basesystem.entity.SysRole;
import com.example.basesystem.entity.SysRoleMenu;
import com.example.basesystem.mapper.SysRoleMapper;
import com.example.basesystem.mapper.SysRoleMenuMapper;
import com.example.basesystem.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色服务实现类
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;

    @Override
    public List<SysRole> getRolesByUserId(Long userId) {
        return sysRoleMapper.selectRolesByUserId(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean assignRoleMenu(Long roleId, List<Long> menuIds) {
        // 删除原有角色菜单关联
        sysRoleMenuMapper.deleteByRoleId(roleId);

        // 添加新的角色菜单关联
        List<SysRoleMenu> roleMenuList = new ArrayList<>();
        for (Long menuId : menuIds) {
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenu.setCreateTime(LocalDateTime.now());
            roleMenuList.add(roleMenu);
        }

        // 批量插入
        if (!roleMenuList.isEmpty()) {
            // 批量插入角色菜单关联
            for (SysRoleMenu roleMenu : roleMenuList) {
                sysRoleMenuMapper.insert(roleMenu);
            }
            return true;
        }

        return true;
    }
}